package com.arui.springsecuritystudy.security;

import com.arui.springsecuritystudy.domain.User;
import com.arui.springsecuritystudy.mapper.UserMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * @Description TODO
 * @Date 2024/4/3 14:32
 * @Created by 10574
 */
@Service
public class UserDetailServiceImpl implements UserDetailsService {
    @Autowired
    private UserMapper userMapper;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        List<User> users = userMapper.selectList(new LambdaQueryWrapper<User>().eq(User::getUserName, username));
        if (CollectionUtils.isEmpty(users)) {
            throw new UsernameNotFoundException("用户不存在");
        }
        if (users.size() > 1) {
            throw new UsernameNotFoundException("系统出错，请稍后重试");
            //TODO 打印error日志 记录到系统
        }
        return new LoginUser(users.get(0));
    }
}
